package com.example.rxjavademo1.presenter;

import android.content.Context;

import com.example.rxjavademo1.contract.TrackingContract;
import com.example.rxjavademo1.entity.TrackingNum;
import com.example.rxjavademo1.http.GlobalRetrofitClient;
import com.example.rxjavademo1.service.TrackingService;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import okhttp3.OkHttpClient;

public class TrackingPresenter implements TrackingContract.ITrackingPresenter {
    public static final int HTTP_SUCCESS = 0;
    public static final int HTTP_FAIL = 1;
    private TrackingContract.ITrackingView mTrackingView;
    private Context mContext;
    private OkHttpClient mClient;

    public TrackingPresenter(TrackingContract.ITrackingView trackingView, Context context) {
        mTrackingView = trackingView;
        mContext = context;
        mClient = new OkHttpClient();
    }

    @Override
    public void getData(String trackingNumber) {//get 异步
        if (mTrackingView != null) {
            mTrackingView.onHttpLoading(true);
        }
        TrackingService service = GlobalRetrofitClient.getInstance().create(TrackingService.class);
        service.getData(trackingNumber)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<TrackingNum>() {
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull TrackingNum trackingNum) {
                        if (mTrackingView != null) {
                            mTrackingView.onHttpLoading(false);
                            mTrackingView.showData(trackingNum);
                        }
                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                        if (mTrackingView != null) {
                            mTrackingView.onHttpLoading(false);
                            mTrackingView.onHttpFail(e.getMessage());
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}